package com.wuzhuo.information.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.wuzhuo.information.utiles.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标方法运行前运行，返回true放行
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws IOException {
        //1，获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url:{}",url);
        //2,判断url路径中是否含有login,包含直接放行
        if (url.contains("login")){
            log.info("登录操作,放行....");
            return true;
        }
        //3,获取请求头中的jwt令牌(token)
        String jwt = req.getHeader("token");
        //4,判断令牌是否存在，如果不存在则报错
        if(!StringUtils.hasLength("jwt")){
            log.info("请求头token为空,未登录呢");
            String notLogin = JSONObject.toJSONString("NOT_LOGIN");
            res.getWriter().write(notLogin);
            return false;
        }
        //5,解析jwt令牌，解析失败则报错
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e){
            //令牌解析失败了
            e.printStackTrace();
            log.info("jwt令牌解析失败，返回未登录信息");
            String notLogin = JSONObject.toJSONString("NOT_LOGIN");
            res.getWriter().write(notLogin);
            return false;
        }
        //6,一切正常放行
        log.info("令牌合法,放行啦");
        return true;
    }


}
